/**
 * Created by lvlq on 16/7/3.
 */
var express = require("express");
var router = express.Router();
var status_enum = require("./status_enum");
var request = require("request");
var activity_enum = require("./play/activity_enum");
var Q = require("q");

/**
 * app 等待二维码扫描 判断当前二维码是否被扫描
 * 定时刷新接口
 */
router.post("/getqueue", function (req, res) {
    var activityId = req.body.activityId;
    var player = req.body.player || 1;
    var returnData = null;
    var Queue = M("index.queue");
    var Record = M("index.record");

    Queue.find({
        where: {
            activityId: activityId,
            player: player,
            status: status_enum.WAIT
        }
    }).then(function (data) {
        returnData = data;

        if (!data) throw new Error("没有数据");
        return Queue.update({
            status: status_enum.PLAY
        }, {
            where: {
                activityId: activityId,
                player: player,
                status: status_enum.WAIT
            }
        });
    }).then(function () {
        var b = new Buffer(returnData.username, 'base64');
        returnData.username = b.toString();

        return Record.find({
            where: {
                participantId: returnData.participantId,
                activityId: activityId
            }
        })
    }).then(function (data) {
        if (data) {
            returnData.record = data;
        } else {
            returnData.record = null;
        }

        console.log(returnData);

        res.json({
            errno: 0,
            data: returnData
        });
    }).catch(function (err) {
        res.json({
            errno: 10001,
            err: err.message
        })
    })
});


/**
 * app 获取结果信息 分数 points 照片 images 视频 video
 * 定时刷新接口
 */
router.post("/getresult", function (req, res) {
    var activityId = req.body.activityId;
    var player = req.body.player || 1;
    // var participantId = req.body.participantId;
    var Queue = M("index.queue");

    Queue.find({
        where: {
            activityId: activityId,
            player: player,
            status: status_enum.RESULT
        }
    }).then(function (data) {
        if (!data) throw new Error("没有提交结果");

        res.json({
            errno: 0,
            data: data
        });
    }).catch(function (err) {
        res.json({
            errno: 1001,
            err: err.message
        });
    });
});


/**
 * app 提交结果接口
 *
 */
router.post("/result", function (req, res) {
    var activityId = req.body.activityId;
    var player = req.body.player || 1;
    var points = req.body.points || 0;
    var url = 'http://republicofsports.adidas.cn/api/participants/score';
    var clientKey = 'sd325SFV3sd23g2';
    var Queue = M("index.queue");

    //获取接口参数
    Queue.find({
        where: {
            activityId: activityId,
            player: player
        }
    }).then(function (data) {
        var record = {
            "participantId": data.participantId,
            "activityId": activityId,
            "points": points,
            "images": data.images,
            "videos": data.videos
        };

        var images = [];
        images.push({
            imageUrl: data.images,
            datetime: new Date().Format("yyyy-MM-dd HH:mm:ss")
        });
        var videos = [];
        videos.push({
            videoUrl: data.videos,
            datetime: new Date().Format("yyyy-MM-dd HH:mm:ss")
        });

        if (activityId == activity_enum.GUINNESS_RECORDS) {
            images[0].imageUrl = 'http://adidas.weixinzjit.com/Public/zs_online.png';
        }

        var post_data = {
            "participantId": data.participantId,
            "activityId": activityId,
            "points": points,
            "clientKey": data.clientKey,
            "images": images,
            "videos": videos
        };

        request({
            url: url,
            method: "POST",
            json: true,
            body: post_data
        }, function (error, response, body) {
            var Log = M("index.log");
            Log.create({
                error: (error && error.message) ? error.message : '',
                response: (response && response.statusCode) ? response.statusCode : '',
                body: body ? JSON.stringify(body) : '',
                data: JSON.stringify(post_data)
            }).then(function () {
                return Queue.update({
                    status: status_enum.END,
                    username: '',
                    points: 0,
                    images: "",
                    videos: "",
                    participantId: 0
                }, {
                    where: {
                        activityId: activityId,
                        player: player
                    }
                });
            }).then(function () {
                return addRecord(record);
            }).then(function () {
                res.json({
                    errno: 0
                });
            }).catch(function (err) {
                res.json({
                    errno: 10001,
                    err: err.message
                });
            });
        });

    }).catch(function (err) {
        res.json({
            errno: 10001,
            err: err.message
        });
    });


});

/**
 * 停止游戏接口
 */
router.post("/stop", function (req, res) {
    var activityId = req.body.activityId;
    var player = req.body.player || 1;
    var Queue = M("index.queue");

    Queue.update({
        status: status_enum.END,
        username: '',
        points: 0,
        images: "",
        videos: "",
        participantId: 0
    }, {
        where: {
            activityId: activityId,
            player: player
        }
    }).then(function () {
        res.json({
            errno: 0
        });
    }).catch(function (err) {
        res.json({
            errno: 10001,
            err: err.message
        });
    });
});


/**
 * app 点击开始接口
 * 标记游戏已经开始
 */
router.post("/begin", function (req, res) {
    var activityId = req.body.activityId;
    var player = req.body.player || 1;
    var Queue = M("index.queue");

    Queue.update({
        status: status_enum.PLAY_BTN
    }, {
        where: {
            activityId: activityId,
            player: player
        }
    }).then(function () {
        res.json({
            errno: 0
        });
    }).catch(function (err) {
        res.json({
            errno: 10001,
            err: err.message
        });
    });
});

//app登陆
router.post("/login", function (req, res) {
    var username = req.body.username;
    var password = req.body.password;

    var User = M("index.user");

    User.find({
        where: {
            username: username,
            password: password
        }
    }).then(function (data) {
        if (!data) throw new Error("用户名密码错误");

        res.json({
            errno: 0
        });
    }).catch(function (err) {
        res.json({
            errno: 10001,
            err: err.message
        });
    })
});

module.exports = router;

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};


var addRecord = function (record) {
    var defer = Q.defer();
    var Record = M("index.record");
    // var post_data = {
    //     "participantId": data.participantId,
    //     "activityId": activityId,
    //     "points": points,
    //     "clientKey": data.clientKey,
    //     "images": images,
    //     "videos": videos
    // };

    Record.find({
        where: {
            participantId: record.participantId,
            activityId: record.activityId
        }
    }).then(function (data) {
        if (data) {
            return Record.update(record, {
                where: {
                    participantId: record.participantId,
                    activityId: record.activityId
                }
            });
        } else {
            return Record.create(record);
        }
    }).then(function () {
        defer.resolve();
    }).catch(function (err) {
        defer.reject(err);
    });

    return defer.promise;
};

router.get('/testrecord', function (req, res) {

    var record = {
        "participantId": 1,
        "activityId": "9",
        "points": req.query.points,
        "images": "",
        "videos": ""
    };

    addRecord(record).then(function () {
        res.json({a: 1});
    }).catch(function (err) {
        res.json(err);
    });

});